//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Web.Routing;
using System.Web.UI;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.Common;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Services;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;
namespace NopSolutions.NopCommerce.Web
{
    public partial class ProductPage : BaseNopFrontendPage
    {
        private IProductService _productService;
        private ISettingService _settingService;
        Product _product = null;

        public ProductPage() {
            _productService = IoC.Resolve<IProductService>();
            _settingService = IoC.Resolve<ISettingService>();

            if (ProductId > 0)
                _product = _productService.GetProductById(ProductId);
        }

        protected override void OnInit(EventArgs e) {
            this.CreateChildControlsTree();
            
            base.OnInit(e);

            Load += new EventHandler(ProductPage_Load);

            //if (Request.RequestContext.RouteData.Route != null) {
            //    Route r = Request.RequestContext.RouteData.Route as Route;
            //    if (r != null && r.Url.StartsWith("produse/")) {
            //        int prodId = 0;
            //        if (!int.TryParse(Request.RequestContext.RouteData.Values["productId"].ToString(), out prodId)) {
            //            if (int.TryParse(Request.RequestContext.RouteData.Values["productId"].ToString().Split('-')[0], out prodId)) {
            //                var prod = this.ProductService.GetProductById(prodId);
            //                var prodSeName = SEOHelper.GetSEName(prod.Name);
            //                Response.RedirectToRoutePermanent("ProductRoute", new { productId = prodId, productName = prodSeName });
            //                Response.End();
            //            }
            //        }
            //    }
            //}            
        }

        void ProductPage_Load(object sender, EventArgs e) {
            if (_product == null || _product.Deleted)
                Response.Redirect(CommonHelper.GetStoreLocation());

            //title, meta
            string title = string.Empty;
            if (!string.IsNullOrEmpty(_product.LocalizedMetaTitle))
                title = _product.LocalizedMetaTitle;
            else {
                title = _product.LocalizedName;
                if (_product.ProductCategories.Count > 0) {
                    bool hasParentCategory = true;
                    var parentCategory = _product.ProductCategories[0].Category;
                    while (hasParentCategory) {
                        title += " - " + parentCategory.LocalizedName;
                        if (parentCategory.ParentCategory == null) {
                            hasParentCategory = false;
                        }
                        else {
                            parentCategory = parentCategory.ParentCategory;
                        }
                    }
                }
            }
            SEOHelper.RenderTitle(this, title, true);
            SEOHelper.RenderMetaTag(this, "description", _product.LocalizedMetaDescription, true);
            SEOHelper.RenderMetaTag(this, "keywords", _product.LocalizedMetaKeywords, true);

            //canonical URL
            if (SEOHelper.EnableUrlRewriting &&
                _settingService.GetSettingValueBoolean("SEO.CanonicalURLs.Products.Enabled")) {
                if (!this.SEName.Equals(SEOHelper.GetProductSEName(_product))) {
                    string canonicalUrl = SEOHelper.GetProductUrl(_product);

                    SEOHelper.RenderCanonicalTag(Page, canonicalUrl);
                }
            }

            if (!Page.IsPostBack) {
                _productService.AddProductToRecentlyViewedList(_product.ProductId);
            }
        }

        private void CreateChildControlsTree() {
            if (_product != null) {
                Control child = null;

                ProductTemplate productTemplate = _product.ProductTemplate;
                if (productTemplate == null)
                    throw new NopException(string.Format("Product template path can not be empty. Product ID={0}", _product.ProductId));

                child = base.LoadControl(productTemplate.TemplatePath);
                this.ProductPlaceHolder.Controls.Add(child);
            }
        }

        public int ProductId {
            get {
                return CommonHelper.RouteStringInt("productId");
            }
        }

        public string SEName {
            get {
                return CommonHelper.QueryString("productName");
            }
        }

        public override PageSslProtectionEnum SslProtected {
            get {
                return PageSslProtectionEnum.No;
            }
        }
    }
}